跳到主要内容

Unity 异常处理

C#中内置的异常类型

C# 中的异常类主要是直接或间接地派生于 System.Exception 类。其中 System.ApplicationException 和 System.SystemException 类是派生于 System.Exception 类的异常类。

  • System.ApplicationException :支持由应用程序生成的异常。所以程序员定义的异常都应派生自该类。
  • System.SystemException :是所有预定义的系统异常的基类。

下表列出了一些派生自 System.SystemException 类的预定义的异常类:

int result = 0;
int num1 = 25;
int num2 = 0;
try
{
result = num1 / num2;
}
catch (DivideByZeroException e) // 捕获除以0的异常
{
Debug.Log(string.Format("Exception caught: {0}", e));
}
finally // 不管是否异常,都会执行
{
Debug.Log(string.Format("Result: {0}", result));
}

// 输出结果
// Exception caught: System.DivideByZeroException: Attempted to divide by zero.
// at ......
// Result: 0

用户自定义异常类型

用户自定义的异常类是派生自 ApplicationException 类

// 自定义异常
public class TempIsZeroException : ApplicationException
{
public TempIsZeroException(string message) : base(message)
{
}
}

// 抛出错误测试
namespace UserDefinedException
{
class TestTemperature
{
public static void ShowTemp(int temperature)
{
if (temperature == 0)
{
// 抛出自定义异常 TempIsZeroException
throw (new TempIsZeroException("Zero Temperature found"));
}
}
static void Main(string[] args)
{
try
{
ShowTemp(0);
}
catch (TempIsZeroException e) // 捕获自定义异常
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}

Debug.LogError 和抛出异常的区别

Debug.LogError("I am an error through Debug.LogError");
throw new Exception("I am an error through new Exception");

当从方法中抛出异常后它将不再执行后面的方法,一般这种抛出异常的时候多半需要终止运行了,而 LogError 只是打印了这个错误信息

所以一般使用 Debug.LogError 就行了

Reference

参考资料 Debug.LogError vs throw new exception 参考资料 【Unity|C#】基础篇(15)——异常处理(try/catch/throw)